<template>
  <div class="package-setting">
    <el-card>
      <div class="table-actions">
        <el-input v-model="search.type" placeholder="箱型" style="width: 120px; margin-right: 8px;" clearable />
        <el-input v-model="search.size" :placeholder="`尺寸 (cm)`" style="width: 120px; margin-right: 8px;" clearable />
        <el-select v-model="search.status" placeholder="状态" style="width: 120px; margin-right: 8px;" clearable>
          <el-option label="全部" value="" />
          <el-option label="启用" value="启用" />
          <el-option label="禁用" value="禁用" />
        </el-select>
        <el-button type="primary" @click="openDialog('add')">新增项目</el-button>
        <!-- <el-button type="success" @click="importDialogVisible = true">批量导入</el-button> -->
      </div>
      <el-table :data="pagedList" style="width: 100%; margin-bottom: 12px;">
        <el-table-column prop="index" label="序号" width="60" />
        <el-table-column prop="type" label="箱型" width="100" />
        <el-table-column prop="packageType" label="包裹类型" width="120" />
        <el-table-column prop="size" label="尺寸(cm)" width="140" />
        <el-table-column prop="volume" label="容积(cm³)" width="120">
          <template #default="scope">
            {{ scope.row.volume }}
          </template>
        </el-table-column>
        <el-table-column prop="maxWeight" label="最大承重(kg)" width="120">
          <template #default="scope">
            {{ scope.row.maxWeight }}
          </template>
        </el-table-column>
        <el-table-column prop="boxWeight" label="箱体重量(kg)" width="120">
          <template #default="scope">
            {{ scope.row.boxWeight }}
          </template>
        </el-table-column>
        <el-table-column prop="cost" label="成本价格(日元)" width="120" />
        <el-table-column prop="stock" label="库存数量" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="disableReason" label="禁用原因" width="120">
          <template #default="scope">
            <span v-if="scope.row.status === '禁用'">{{ scope.row.disableReason || '-' }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="图片" width="80">
          <template #default="scope">
            <el-image v-if="scope.row.image" :src="scope.row.image" style="width:48px;height:48px;object-fit:contain;" :preview-src-list="[scope.row.image]" preview-teleported />
            <span v-else style="color:#bbb;">无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="toggleStatus(scope.row)">{{ scope.row.status === '启用' ? '禁用' : '启用' }}</el-button>
            <el-button size="small" @click="openDialog('edit', scope.row, scope.$index)">编辑</el-button>
            <el-button size="small" @click="showHistory(scope.row)">历史</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="filteredList.length"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[10, 20, 50]"
        style="margin-top: 12px; text-align: right;"
      />
      <el-dialog v-model="dialog.visible" :title="dialog.mode === 'add' ? '新增包裹' : '编辑包裹'" width="400px" :close-on-click-modal="false">
        <el-form :model="dialog.form" label-width="100px">
          <el-form-item label="箱型" required>
            <el-input v-model="dialog.form.type" />
          </el-form-item>
          <el-form-item label="包裹类型" required>
            <el-select v-model="dialog.form.packageType" style="width: 180px">
              <el-option label="普通箱" value="普通箱" />
              <el-option label="冷链箱" value="冷链箱" />
              <el-option label="易碎品箱" value="易碎品箱" />
              <el-option label="定制箱" value="定制箱" />
            </el-select>
          </el-form-item>
          <el-form-item label="尺寸(cm)" required>
            <el-input v-model="dialog.form.size" placeholder="长×宽×高 (cm)" />
          </el-form-item>
          <el-form-item label="容积(cm³)" required>
            <el-input-number v-model="dialog.form.volume" :min="0" style="width: 180px" />
          </el-form-item>
          <el-form-item label="最大承重(kg)" required>
            <el-input-number v-model="dialog.form.maxWeight" :min="0" style="width: 180px" />
          </el-form-item>
          <el-form-item label="箱体重量(kg)" required>
            <el-input-number v-model="dialog.form.boxWeight" :min="0" style="width: 180px" />
          </el-form-item>
          <el-form-item label="成本价格(¥)" required>
            <el-input-number v-model="dialog.form.cost" :min="0" style="width: 180px" />
          </el-form-item>
          <el-form-item label="库存数量" required>
            <el-input-number v-model="dialog.form.stock" :min="0" style="width: 180px" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="dialog.form.status" style="width: 120px">
              <el-option label="启用" value="启用" />
              <el-option label="禁用" value="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item label="箱型图片">
            <el-upload
              class="upload-demo"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              :http-request="customUpload"
              accept="image/*"
            >
              <el-image v-if="dialog.form.image" :src="dialog.form.image" style="width:48px;height:48px;object-fit:contain;margin-right:8px;" />
              <el-button type="primary">上传图片</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="savePackage">保存</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="historyDialog.visible" title="历史变更记录" width="600px" :close-on-click-modal="false">
        <el-table :data="historyDialog.list" style="width:100%">
          <el-table-column prop="time" label="时间" width="180" />
          <el-table-column prop="action" label="操作" width="80" />
          <el-table-column label="变更内容">
            <template #default="scope">
              <div v-if="scope.row.diff && scope.row.diff.length">
                <div v-for="item in scope.row.diff" :key="item.key" style="font-size:13px;line-height:1.8;">
                  <b>{{ item.label }}：</b> <span style="color:#888">{{ item.oldValue }}</span> <span style="color:#409EFF">→</span> <span style="color:#222">{{ item.newValue }}</span>
                </div>
              </div>
              <div v-else style="color:#bbb;">无变更</div>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <el-button @click="historyDialog.visible = false">关闭</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="importDialogVisible" title="批量导入包裹" width="400px" :close-on-click-modal="false">
        <div style="margin-bottom: 12px;">
          <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
        </div>
        <el-upload
          class="upload-demo"
          drag
          action=""
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          accept=".xlsx,.xls"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <template #footer>
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImport">导入</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="disableDialog.visible" title="禁用包裹" width="400px" :close-on-click-modal="false">
        <el-form label-width="80px">
          <el-form-item label="禁用原因" required>
            <el-input v-model="disableDialog.reason" placeholder="请输入禁用原因" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="disableDialog.remark" placeholder="可填写详细说明" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="disableDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmDisable">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import * as XLSX from 'xlsx'
const packageList = ref([
  { index: 1, type: '小箱', packageType: '普通箱', size: '30×20×15', volume: 9000, maxWeight: 10, boxWeight: 1.2, cost: 12, status: '启用', image: '', stock: 100, history: [], disableReason: '', disableRemark: '' },
  { index: 2, type: '中箱', packageType: '冷链箱', size: '50×30×30', volume: 45000, maxWeight: 20, boxWeight: 2.5, cost: 20, status: '启用', image: '', stock: 50, history: [], disableReason: '', disableRemark: '' },
  { index: 3, type: '大箱', packageType: '易碎品箱', size: '70×50×40', volume: 140000, maxWeight: 40, boxWeight: 4.8, cost: 35, status: '禁用', image: '', stock: 10, history: [], disableReason: '破损', disableRemark: '箱体有裂痕' }
])
const page = ref({ current: 1, size: 10 })
const search = ref({ type: '', size: '', status: '' })
const filteredList = computed(() => {
  return packageList.value.filter(item => {
    return (!search.value.type || item.type.includes(search.value.type)) &&
      (!search.value.size || item.size.includes(search.value.size)) &&
      (!search.value.status || item.status === search.value.status)
  })
})
const pagedList = computed(() => {
  const start = (page.value.current - 1) * page.value.size
  return filteredList.value.slice(start, start + page.value.size)
})
const dialog = ref({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: { index: 0, type: '', packageType: '普通箱', size: '', volume: 0, maxWeight: 0, boxWeight: 0, cost: 0, status: '启用', image: '', stock: 0 },
  editIndex: -1
})
function openDialog(mode: 'add' | 'edit', row?: any, idx?: number) {
  dialog.value.mode = mode
  if (mode === 'add') {
    dialog.value.form = { index: 0, type: '', packageType: '普通箱', size: '', volume: 0, maxWeight: 0, boxWeight: 0, cost: 0, status: '启用', image: '', stock: 0 }
    dialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    dialog.value.form = { ...row }
    dialog.value.editIndex = idx
  }
  dialog.value.visible = true
}
const fieldLabels = {
  type: '箱型',
  packageType: '包裹类型',
  size: '尺寸',
  volume: '容积',
  maxWeight: '最大承重',
  boxWeight: '箱体重量',
  cost: '成本价格',
  stock: '库存数量',
  status: '状态',
  image: '图片',
  disableReason: '禁用原因',
  disableRemark: '禁用备注'
}
function getDiff(oldData, newData) {
  const keys = Object.keys(fieldLabels)
  const diff = []
  keys.forEach(key => {
    if (oldData && oldData[key] !== undefined && newData && newData[key] !== undefined && oldData[key] !== newData[key]) {
      diff.push({ key, label: fieldLabels[key], oldValue: oldData[key], newValue: newData[key] })
    }
  })
  return diff
}
function savePackage() {
  const idx = dialog.value.editIndex
  const now = new Date().toLocaleString()
  if (dialog.value.mode === 'add') {
    packageList.value.push({ ...dialog.value.form, index: packageList.value.length > 0 ? Math.max(...packageList.value.map(i => i.index)) + 1 : 1, history: [{ time: now, action: '新增', diff: [] }] })
  } else if (idx > -1) {
    const old = { ...packageList.value[idx] }
    const diff = getDiff(old, dialog.value.form)
    packageList.value[idx] = { ...dialog.value.form, history: [...(old.history || []), { time: now, action: '编辑', diff }] }
  }
  dialog.value.visible = false
}
function toggleStatus(row: any) {
  if (row.status === '启用') {
    disableDialog.value = { visible: true, row, reason: '', remark: '' }
  } else {
    const old = { ...row }
    row.status = '启用'
    row.disableReason = ''
    row.disableRemark = ''
    const diff = getDiff(old, row)
    row.history = [...(row.history || []), { time: new Date().toLocaleString(), action: '启用', diff }]
  }
}
function confirmDisable() {
  if (!disableDialog.value.reason) return
  const row = disableDialog.value.row
  const old = { ...row }
  row.status = '禁用'
  row.disableReason = disableDialog.value.reason
  row.disableRemark = disableDialog.value.remark
  const diff = getDiff(old, row)
  row.history = [...(row.history || []), { time: new Date().toLocaleString(), action: '禁用', diff }]
  disableDialog.value.visible = false
}
function handleImageSuccess(response, file) {
  dialog.value.form.image = file.url || file.response?.url || ''
}
function beforeImageUpload(file) {
  const isImg = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImg) this.$message.error('只能上传图片文件！')
  if (!isLt2M) this.$message.error('图片大小不能超过2MB！')
  return isImg && isLt2M
}
function customUpload(option) {
  // mock本地上传，直接转base64
  const reader = new FileReader()
  reader.onload = e => {
    dialog.value.form.image = e.target.result as string
    option.onSuccess && option.onSuccess({}, option.file)
  }
  reader.readAsDataURL(option.file)
}
const historyDialog = ref({ visible: false, list: [] })
function showHistory(row) {
  historyDialog.value.list = row.history || []
  historyDialog.value.visible = true
}
const importDialogVisible = ref(false)
let importFile = null
function downloadTemplate() {
  const wsData = [
    ['箱型','包裹类型','尺寸','容积','最大承重','箱体重量','成本价格','库存数量','状态'],
    ['小箱','普通箱','30×20×15',9000,10,1.2,12,100,'启用']
  ]
  const ws = XLSX.utils.aoa_to_sheet(wsData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '模板')
  XLSX.writeFile(wb, '包裹导入模板.xlsx')
}
function handleFileChange(file) {
  importFile = file.raw
}
function handleImport() {
  if (!importFile) return
  const reader = new FileReader()
  reader.onload = e => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const sheet = workbook.Sheets[workbook.SheetNames[0]]
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 })
    rows.shift() // 去掉表头
    rows.forEach(row => {
      if (!row[0]) return
      packageList.value.push({
        index: packageList.value.length > 0 ? Math.max(...packageList.value.map(i => i.index)) + 1 : 1,
        type: row[0],
        packageType: row[1],
        size: row[2],
        volume: Number(row[3]),
        maxWeight: Number(row[4]),
        boxWeight: Number(row[5]),
        cost: Number(row[6]),
        stock: Number(row[7]),
        status: row[8],
        image: '',
        history: [{ time: new Date().toLocaleString(), action: '批量导入', diff: [] }]
      })
    })
    importDialogVisible.value = false
    importFile = null
  }
  reader.readAsArrayBuffer(importFile)
}
const disableDialog = ref({ visible: false, row: null, reason: '', remark: '' })
</script>

<style scoped>
.package-setting {
  padding: 16px;
}
.table-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}
.unit-switch-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style> 